import qs from 'qs';
import _ from 'lodash';
import Form from '../../../../lib/form';
import utils from '../../utils';
import styles from './detail.less';
import { Table } from 'antd';
import React, {
  useEffect,
  useState,
  useMemo,
  useCallback,
  useReducer,
} from 'react';
import { useRequest, useMount } from 'ahooks';
// import TableList from './table.tsx';

const FormComponent = React.memo(Form, (prevProps, nextProps) => {
  return _.isEqual(prevProps.form.components, nextProps.form.components);
});
const TableComponent = React.memo(Table);
const { storage } = utils;

const getOld = (id: string): any => {
  const oldArr = storage.get('formio_demo_save') || [];
  const oldVal = oldArr.find((i) => i.id == id);
  return oldVal;
};

const exec = async (params: any) => {
  const [url, options] = computedQuery(params);
  const res = await fetch(url, options).then((res) => res.json());

  if (res.code === 0) {
    return res.data || [];
  }
  return [];
};

const computedQuery = (params: any): any => {
  let url = '';
  let query = {};
  let options = {};
  options.headers = {
    Authorization: 'Bearer 4FC67B1921CE568C7EED3BA1ACAAF84B',
    'content-type': 'application/json;charset=UTF-8',
  };
  params = params || {};
  const oporate = params.oporate || 'select';

  if (oporate == 'select') {
    const {
      host,
      port,
      userName,
      password,
      dbName,
      tableName,
      parameter,
    } = params;
    const queryies = {
      host,
      port,
      userName,
      password,
      dbName,
      tableName,
      parameter,
    };
    const queryiesStr = qs.stringify(queryies, { allowDots: true });
    url = `/cid-cnn-runtime-job/mysql/db/table/rows?${queryiesStr}`;
    // query = { host, port, userName, password, dbName, tableName, parameter };
    options.method = 'GET';
  }

  if (oporate == 'delete') {
    const {
      host,
      port,
      userName,
      password,
      dbName,
      tableName,
      columns,
      parameter,
    } = params;
    options.body = JSON.stringify({
      host,
      port,
      userName,
      password,
      dbName,
      tableName,
      columns,
      parameter,
    });
    url = '/cid-cnn-runtime-job/mysql/db/table/rows';
    options.method = 'DELETE';
  }

  if (oporate == 'update') {
    const {
      host,
      port,
      userName,
      password,
      dbName,
      tableName,
      parameter,
      updateColumnValues,
    } = params;
    options.body = JSON.stringify({
      host,
      port,
      userName,
      password,
      dbName,
      tableName,
      parameter,
      updateColumnValues,
    });
    url = '/cid-cnn-runtime-job/mysql/db/table/rows';
    options.method = 'PATCH';
  }

  if (oporate == 'insert') {
    const {
      host,
      port,
      userName,
      password,
      dbName,
      tableName,
      updateColumns,
    } = params;
    options.body = JSON.stringify({
      host,
      port,
      userName,
      password,
      dbName,
      tableName,
      updateColumns,
    });
    url = '/cid-cnn-runtime-job/mysql/db/table/row';
    options.method = 'POST';
  }

  return [url, options];
};

const computedVal = (data) => {
  const columns: any[] = [];
  const rows: any[] = [];

  return [columns, rows];
};

export default function DetailPage(props: Props) {
  const params = props.match && props.match.params ? props.match.params : {};
  const isNew = params && params.id ? false : true;
  const id = isNew ? Math.random().toString(36).slice(-6) : params.id;

  let components: ListData[] = [];
  const oldVal = getOld(id);
  if (oldVal) components = oldVal.schema.components;

  const [columns, setColumns] = useState([]);
  const [rows, setRows] = useState([]);

  const execCommond = async (params: any) => {
    // 先执行条件
    let data = await exec(params);
    // 再查询下全部数据
    if (params && params.oporate != 'select') {
      const { host, port, userName, password, dbName, tableName } = params;
      const selectParams = {
        host,
        port,
        userName,
        password,
        dbName,
        tableName,
        oporate: 'select',
      };
      data = await exec(selectParams);
    }

    data = data || [];
    // const outKeys = params.outKeys ||
    // const columns = data[0]
    //   ? Object.keys(data[0]).map((val, i) => {
    //       return { title: val, dataIndex: val, key: i };
    //     })
    //   : [];
    let columns = [];
    if (data[0]) {
      const outKeys =
        params.outKeys && params.outKeys.length
          ? params.outKeys.map((i) => i.columnName)
          : Object.keys(data[0]);
      columns = outKeys.map((val, i) => {
        return { title: val, dataIndex: val, key: i };
      });
    }

    const rows = data.map((val, i) => {
      val.key = i;
      return val;
    });
    setColumns(columns);
    setRows(rows);
  };

  const { run } = useRequest(execCommond);

  return (
    <div className={styles.formbox}>
      <div className={styles.formcontainer}>
        <FormComponent
          form={{ components }}
          options={{ language: 'zh' }}
          onLoadParams={(params: any) => {
            run(params);
          }}
        ></FormComponent>
      </div>

      <div className={styles.tablecontainer}>
        <Table columns={columns} dataSource={rows}></Table>
      </div>
    </div>
  );
}
